<template>
  <div class="student-form">
    <div class="page-title">
      {{ isEdit ? '编辑学生' : '添加学生' }}
    </div>
    
    <a-card class="form-container">
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        @finish="handleSubmit"
      >
        <!-- 基本信息 -->
        <a-divider orientation="left">基本信息</a-divider>
        
        <a-form-item label="学号" name="studentId">
          <a-input
            v-model:value="formData.studentId"
            placeholder="请输入学号"
            :disabled="isEdit"
          />
        </a-form-item>
        
        <a-form-item label="姓名" name="name">
          <a-input
            v-model:value="formData.name"
            placeholder="请输入学生姓名"
          />
        </a-form-item>
        
        <a-form-item label="性别" name="gender">
          <a-radio-group v-model:value="formData.gender">
            <a-radio value="M">男</a-radio>
            <a-radio value="F">女</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="出生日期" name="birthDate">
          <a-date-picker
            v-model:value="formData.birthDate"
            placeholder="请选择出生日期"
            style="width: 100%"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        
        <a-form-item label="身份证号" name="idCard">
          <a-input
            v-model:value="formData.idCard"
            placeholder="请输入身份证号"
          />
        </a-form-item>
        
        <a-form-item label="联系电话" name="phone">
          <a-input
            v-model:value="formData.phone"
            placeholder="请输入联系电话"
          />
        </a-form-item>
        
        <!-- 学籍信息 -->
        <a-divider orientation="left">学籍信息</a-divider>
        
        <a-form-item label="班级" name="classId">
          <a-select
            v-model:value="formData.classId"
            placeholder="请选择班级"
            style="width: 100%"
          >
            <a-select-option
              v-for="cls in classList"
              :key="cls.id"
              :value="cls.id"
            >
              {{ cls.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="入学日期" name="enrollmentDate">
          <a-date-picker
            v-model:value="formData.enrollmentDate"
            placeholder="请选择入学日期"
            style="width: 100%"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        
        <a-form-item label="学生状态" name="status">
          <a-select
            v-model:value="formData.status"
            placeholder="请选择学生状态"
            style="width: 100%"
          >
            <a-select-option value="active">在读</a-select-option>
            <a-select-option value="graduated">已毕业</a-select-option>
            <a-select-option value="transferred">已转学</a-select-option>
            <a-select-option value="suspended">休学</a-select-option>
            <a-select-option value="expelled">退学</a-select-option>
          </a-select>
        </a-form-item>
        
        <!-- 家庭信息 -->
        <a-divider orientation="left">家庭信息</a-divider>
        
        <a-form-item label="家庭地址" name="address">
          <a-textarea
            v-model:value="formData.address"
            placeholder="请输入家庭地址"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="监护人姓名" name="guardianName">
          <a-input
            v-model:value="formData.guardianName"
            placeholder="请输入监护人姓名"
          />
        </a-form-item>
        
        <a-form-item label="监护人电话" name="guardianPhone">
          <a-input
            v-model:value="formData.guardianPhone"
            placeholder="请输入监护人电话"
          />
        </a-form-item>
        
        <a-form-item label="与学生关系" name="guardianRelation">
          <a-select
            v-model:value="formData.guardianRelation"
            placeholder="请选择与学生关系"
            style="width: 100%"
          >
            <a-select-option value="father">父亲</a-select-option>
            <a-select-option value="mother">母亲</a-select-option>
            <a-select-option value="grandfather">祖父</a-select-option>
            <a-select-option value="grandmother">祖母</a-select-option>
            <a-select-option value="other">其他</a-select-option>
          </a-select>
        </a-form-item>
        
        <!-- 其他信息 -->
        <a-divider orientation="left">其他信息</a-divider>
        
        <a-form-item label="特长爱好" name="hobbies">
          <a-textarea
            v-model:value="formData.hobbies"
            placeholder="请输入学生的特长爱好"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="健康状况" name="healthStatus">
          <a-select
            v-model:value="formData.healthStatus"
            placeholder="请选择健康状况"
            style="width: 100%"
          >
            <a-select-option value="excellent">优秀</a-select-option>
            <a-select-option value="good">良好</a-select-option>
            <a-select-option value="fair">一般</a-select-option>
            <a-select-option value="poor">较差</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="备注" name="remarks">
          <a-textarea
            v-model:value="formData.remarks"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </a-form-item>
        
        <!-- 操作按钮 -->
        <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
          <a-space>
            <a-button type="primary" html-type="submit" :loading="loading">
              {{ isEdit ? '更新' : '保存' }}
            </a-button>
            <a-button @click="handleCancel">
              取消
            </a-button>
            <a-button v-if="!isEdit" @click="handleReset">
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { studentApi } from '@/api'

// 验证身份证号
const validateIdCard = (idCard) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return reg.test(idCard)
}

// 验证手机号
const validatePhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

const router = useRouter()
const route = useRoute()

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 班级列表
const classList = ref([
  { id: 'class1', name: '一年级1班' },
  { id: 'class2', name: '一年级2班' },
  { id: 'class3', name: '二年级1班' },
  { id: 'class4', name: '二年级2班' },
  { id: 'class5', name: '三年级1班' },
  { id: 'class6', name: '三年级2班' }
])

// 表单数据
const formData = reactive({
  studentId: '',
  name: '',
  gender: 'M',
  birthDate: null,
  idCard: '',
  phone: '',
  classId: undefined,
  enrollmentDate: null,
  status: 'active',
  address: '',
  guardianName: '',
  guardianPhone: '',
  guardianRelation: undefined,
  hobbies: '',
  healthStatus: 'good',
  remarks: ''
})

// 表单验证规则
const rules = {
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^S\d{7}$/, message: '学号格式不正确，应为S开头的8位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value && !validateIdCard(value)) {
          return Promise.reject('身份证号格式不正确')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value && !validatePhone(value)) {
          return Promise.reject('手机号格式不正确')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  classId: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  enrollmentDate: [
    { required: true, message: '请选择入学日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择学生状态', trigger: 'change' }
  ],
  guardianName: [
    { required: true, message: '请输入监护人姓名', trigger: 'blur' }
  ],
  guardianPhone: [
    { required: true, message: '请输入监护人电话', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value && !validatePhone(value)) {
          return Promise.reject('监护人电话格式不正确')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  guardianRelation: [
    { required: true, message: '请选择与学生关系', trigger: 'change' }
  ]
}

// 提交表单
const handleSubmit = async (values) => {
  try {
    loading.value = true
    
    // 处理日期格式
    const submitData = {
      ...values,
      birthDate: values.birthDate ? dayjs(values.birthDate).format('YYYY-MM-DD') : null,
      enrollmentDate: values.enrollmentDate ? dayjs(values.enrollmentDate).format('YYYY-MM-DD') : null
    }
    
    if (isEdit.value) {
      // 更新学生信息
      await studentApi.updateStudent(route.params.id, submitData)
      message.success('学生信息更新成功')
    } else {
      // 添加新学生
      await studentApi.addStudent(submitData)
      message.success('学生添加成功')
    }
    
    // 返回学生列表页面
    router.push('/students')
    
  } catch (error) {
    console.error('提交失败:', error)
    message.error(error.message || (isEdit.value ? '更新失败' : '添加失败'))
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.back()
}

// 重置表单
const handleReset = () => {
  formRef.value.resetFields()
}

// 加载学生详情（编辑模式）
const loadStudentDetail = async () => {
  if (!isEdit.value) return
  
  try {
    loading.value = true
    
    // 调用API获取学生详情
    const response = await studentApi.getStudentDetail(route.params.id)
    
    // 填充表单数据
    Object.assign(formData, {
      ...response,
      birthDate: response.birthDate ? dayjs(response.birthDate) : null,
      enrollmentDate: response.enrollmentDate ? dayjs(response.enrollmentDate) : null
    })
    
  } catch (error) {
    console.error('加载学生详情失败:', error)
    message.error(error.message || '加载学生详情失败')
    // 如果加载失败，返回列表页
    router.push('/students')
  } finally {
    loading.value = false
  }
}

// 生成学生ID
const generateStudentId = async () => {
  try {
    const response = await studentApi.generateStudentId()
    formData.studentId = response.studentId || response
  } catch (error) {
    console.error('生成学生ID失败:', error)
    // 如果API失败，使用本地生成逻辑
    const year = new Date().getFullYear()
    const timestamp = Date.now().toString().slice(-4)
    formData.studentId = `S${year}${timestamp}`
  }
}

// 组件挂载时的操作
onMounted(async () => {
  if (isEdit.value) {
    loadStudentDetail()
  } else {
    // 新增模式下设置默认值
    formData.enrollmentDate = dayjs()
    // 自动生成学生ID
    await generateStudentId()
  }
})
</script>

<style scoped>
.student-form {
  padding: 0;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 8px;
}

.ant-divider {
  margin: 24px 0 16px 0;
  font-weight: 500;
}

@media (max-width: 768px) {
  .form-container {
    margin: 0;
  }
  
  .ant-form-item {
    margin-bottom: 16px;
  }
  
  :deep(.ant-form-item-label) {
    text-align: left;
  }
  
  :deep(.ant-col-6) {
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  :deep(.ant-col-18) {
    flex: 0 0 100%;
    max-width: 100%;
  }
}
</style>